'use strict';

const _ = require('lodash');

exports.index = async ctx => {
  const { query } = ctx.request;
  console.log('exports query', query);
  const currentUser = await ctx.model.User.findByPk(ctx.state.user.sub);
  console.log('exports.index = async currentUser', currentUser);
  console.log('exports.index = async currentUser ctx.state.user.sub', ctx.state.user.sub);
  let pageSize = 10;
  if (query.pageSize) pageSize = Number(query.pageSize);
  const where = {};
  const { nameLike, storeClassId, storeType, type, userId, status, storeCityId } = query;
  if (currentUser.role === 'facilitator') where.facilitatorId = ctx.state.user.sub;
  if (nameLike) where.name = { [ctx.model.Op.like]: `%${nameLike}%` };
  if (storeClassId) where.storeClassId = storeClassId;
  if (storeType) where.storeType = storeType;
  if (userId) where.userId = userId;
  if (status) where.status = status;
  if (storeCityId) where.storeCityId = storeCityId;
  const options = {
    limit: pageSize,
    offset: query.currentPage ? pageSize * (query.currentPage - 1) : 0,
    where,
  };
  if (type === 'followed') {
    options.include = [
      {
        as: 'users',
        model: ctx.model.User,
        where: { id: ctx.state.user.sub },
      },
    ];
  }
  const {
    count: total, rows: list,
  } = await ctx.model.Store.findAndCountAll(options);
  ctx.body = {
    list,
    pagination: {
      total,
      pageSize,
      current: parseInt(query.currentPage, 10) || 1,
    },
  };
};


exports.create = async ctx => {
  ctx.validate({
    name: { type: 'string' },
    address: { type: 'string' },
    phone: { type: 'string' },
    storeType: { type: 'string' },
    storeClassId: { type: 'int' },
    storeCityId: { type: 'int' },
    longitude: { type: 'string' },
    latitude: { type: 'string' },
    imageHash: { type: 'string', required: false },
    commissionRatio: { type: 'string' },
    fileHash: { type: 'string', required: false },
    imageHashes: { type: 'array', itemType: 'string', required: false },
  });
  const { name,
    address,
    phone,
    storeClassId,
    commissionRatio,
    longitude,
    latitude,
    fileHash,
    imageHash,
    imageHashes,
    storeType,
    storeCityId,
  } = ctx.request.body;
  const currentUser = await ctx.model.User.findByPk(ctx.state.user.sub);
  console.log('currentUser', currentUser);
  const { role } = currentUser;
  switch (role) {
    case 'admin':
      if (imageHash) await ctx.service.file.record('image', imageHash);
      if (fileHash) await ctx.service.file.record('image', fileHash);
      if (storeType === 'reserve') {
        const data = { name, address, phone, storeType, storeClassId, storeCityId, commissionRatio, longitude, latitude, imageHash, fileHash, imageHashes };
        data.status = 'published';
        const phoneUser = await ctx.model.Phone.findByPk(phone);
        console.log('phoneUser await ctx.model.Phone', phoneUser);
        if (!phoneUser) {
          const newUser = await ctx.model.User.create({ role: 'general' });
          console.log('phoneUser await ctx.model.Phone newUser', newUser);
          await ctx.model.Phone.create({ number: phone, userId: newUser.id });
          data.userId = newUser.id;
        } else {
          data.userId = phoneUser.userId;
        }
        console.log('datadatadatadatadatadatadata', data);
        const store = await ctx.model.Store.create(_.pickBy(
          _.pick(
            data,
            [ 'name', 'status', 'address', 'phone', 'storeType', 'storeCityId', 'userId', 'commissionRatio', 'storeClassId', 'longitude', 'latitude', 'imageHash', 'fileHash' ]
          ),
          value => value !== null
        ));
        if (imageHashes && imageHashes.length > 0) {
          await ctx.service.file.bulkRecord('image', imageHashes);
          await ctx.model.StoreImage.bulkCreate(imageHashes.map(imageHash => ({
            imageHash, storeId: store.id,
          })));
        }
        ctx.body = store;
      } else {
        const data = { name, address, phone, storeType, storeClassId, storeCityId, commissionRatio, longitude, latitude, imageHash, fileHash, imageHashes };
        data.status = 'published';
        const phoneUser = await ctx.model.Phone.findByPk(phone);
        if (!phoneUser) {
          const newUser = await ctx.model.User.create({ role: 'general' });
          await ctx.model.Phone.create({ number: phone, userId: newUser.id });
          data.userId = newUser.id;
        } else {
          data.userId = phoneUser.userId;
        }
        console.log('datadatadatadatadatadatadata', data);
        const store = await ctx.model.Store.create(_.pickBy(
          _.pick(
            data,
            [ 'name', 'status', 'address', 'phone', 'storeType', 'storeCityId', 'userId', 'commissionRatio', 'storeClassId', 'longitude', 'latitude', 'imageHash', 'fileHash' ]
          ),
          value => value !== null
        ));
        if (imageHashes && imageHashes.length > 0) {
          await ctx.service.file.bulkRecord('image', imageHashes);
          await ctx.model.StoreImage.bulkCreate(imageHashes.map(imageHash => ({
            imageHash, storeId: store.id,
          })));
        }
        ctx.body = store;
      }
      break;
    case 'facilitator':
      if (storeType === 'store') {
        const data = { name, address, phone, storeType, storeCityId, storeClassId, commissionRatio, longitude, latitude, imageHash, fileHash, imageHashes, facilitatorId: currentUser.id };
        const phoneUser = await ctx.model.Phone.findByPk(phone);
        if (fileHash) await ctx.service.file.record('image', fileHash);
        if (imageHash) await ctx.service.file.record('image', imageHash);
        if (!phoneUser) {
          const newUser = await ctx.model.User.create({ role: 'general' });
          await ctx.model.Phone.create({ number: phone, userId: newUser.id });
          data.userId = newUser.id;
        } else {
          data.userId = phoneUser.userId;
        }
        console.log('storeType === facilitator data', data);
        const store = await ctx.model.Store.create(_.pickBy(
          _.pick(
            data,
            [ 'name', 'status', 'address', 'phone', 'storeType', 'storeCityId', 'userId', 'commissionRatio', 'storeClassId', 'longitude', 'latitude', 'imageHash', 'fileHash', 'imageHashes', 'facilitatorId' ]
          ),
          value => value !== null
        ));
        if (imageHashes && imageHashes.length > 0) {
          await ctx.service.file.bulkRecord('image', imageHashes);
          await ctx.model.StoreImage.bulkCreate(imageHashes.map(imageHash => ({
            imageHash, storeId: store.id,
          })));
        }
        ctx.body = store;
      } else {
        const data = { name, address, phone, storeType, storeCityId, storeClassId, commissionRatio, longitude, latitude, imageHash, fileHash, imageHashes, facilitatorId: currentUser.id };
        if (fileHash) await ctx.service.file.record('image', fileHash);
        if (imageHash) await ctx.service.file.record('image', imageHash);
        const phoneUser = await ctx.model.Phone.findByPk(phone);
        if (!phoneUser) {
          const newUser = await ctx.model.User.create({ role: 'general' });
          await ctx.model.Phone.create({ number: phone, userId: newUser.id });
          data.userId = newUser.id;
        } else {
          data.userId = phoneUser.userId;
        }
        console.log('await ctx.model.Store.create data', data);
        const store = await ctx.model.Store.create(_.pickBy(
          _.pick(
            data,
            [ 'name', 'status', 'address', 'phone', 'storeType', 'storeCityId', 'userId', 'commissionRatio', 'storeClassId', 'longitude', 'latitude', 'imageHash', 'fileHash', 'imageHashes', 'facilitatorId' ]
          ),
          value => value !== null
        ));
        if (imageHashes && imageHashes.length > 0) {
          await ctx.service.file.bulkRecord('image', imageHashes);
          await ctx.model.StoreImage.bulkCreate(imageHashes.map(imageHash => ({
            imageHash, storeId: store.id,
          })));
        }
        ctx.body = store;
      }
      break;
    default:
  }
};

exports.show = async ctx => {
  const options = {
    include: [
      {
        model: ctx.model.StoreImage,
      },
    ],
  };
  const currentUser = await ctx.model.User.findByPk(ctx.state.user.sub);
  console.log('participated currentUser', currentUser);
  const store = await ctx.model.Store.findByPk(ctx.params.id, options);
  const followed = await store.hasUser(currentUser);
  console.log('exports.show followed', followed);
  store.dataValues.followed = followed;
  console.log('exports.show followed store', store);
  if (store) {
    ctx.body = store;
  } else {
    ctx.status = 404;
  }
};

exports.update = async ctx => {
  ctx.validate({
    name: { type: 'string', required: false },
    address: { type: 'string', required: false },
    phone: { type: 'string', required: false },
    storeType: { type: 'string', required: false },
    storeClassId: { type: 'int', required: false },
    storeCityId: { type: 'int', required: false },
    longitude: { type: 'string', required: false },
    latitude: { type: 'string', required: false },
    imageHash: { type: 'string', required: false },
    commissionRatio: { type: 'string', required: false },
    fileHash: { type: 'string', required: false },
    imageHashes: { type: 'array', itemType: 'string', required: false },
    status: { type: 'enum', values: [ 'draft', 'published' ], required: false },
  });
  const { fileHash, imageHash, imageHashes } = ctx.request.body;
  const currentUser = await ctx.model.User.findByPk(ctx.state.user.sub);
  const store = await ctx.model.Store.findOne({ where: { userId: currentUser.id } });
  if (store && store.userId === currentUser.id) {
    console.log('store && store.userId === currentUser.id');
    if (imageHash) await ctx.service.file.record('image', imageHash);
    if (fileHash) await ctx.service.file.record('image', fileHash);
    if (imageHashes && imageHashes.length > 0) {
      // 删除旧图
      await ctx.model.StoreImage.destroy({ where: { storeId: store.id } });
      // 记录到file
      await ctx.service.file.bulkRecord('image', imageHashes);
      // 保存多图
      await ctx.model.StoreImage.bulkCreate(imageHashes.map(imageHash => ({
        imageHash, storeId: store.id,
      })));
    }
    ctx.body = await store.update(_.pickBy(
      _.pick(
        ctx.request.body,
        [ 'name', 'status', 'address', 'phone', 'storeType', 'storeCityId', 'commissionRatio', 'storeClassId', 'longitude', 'latitude', 'imageHash', 'fileHash' ]
      ),
      value => value !== null
    ));
  }
  const { role } = currentUser;
  switch (role) {
    case 'admin': {
      const store = await ctx.model.Store.findByPk(ctx.params.id);
      if (imageHash) await ctx.service.file.record('image', imageHash);
      if (fileHash) await ctx.service.file.record('image', fileHash);
      if (store) {
        if (imageHashes && imageHashes.length > 0) {
          // 删除旧图
          await ctx.model.StoreImage.destroy({ where: { storeId: store.id } });
          // 记录到file
          await ctx.service.file.bulkRecord('image', imageHashes);
          // 保存多图
          await ctx.model.StoreImage.bulkCreate(imageHashes.map(imageHash => ({
            imageHash, storeId: store.id,
          })));
        }
        ctx.body = await store.update(_.pickBy(
          _.pick(
            ctx.request.body,
            [ 'name', 'status', 'address', 'phone', 'storeType', 'storeCityId', 'commissionRatio', 'storeClassId', 'longitude', 'latitude', 'imageHash', 'fileHash' ]
          ),
          value => value !== null
        ));
      } else {
        ctx.status = 404;
      }
    }
      break;
    case 'facilitator': {
      const store = await ctx.model.Store.findByPk(ctx.params.id);
      if (store) {
        if (imageHashes && imageHashes.length > 0) {
          // 删除旧图
          await ctx.model.StoreImage.destroy({ where: { storeId: store.id } });
          // 记录到file
          await ctx.service.file.bulkRecord('image', imageHashes);
          // 保存多图
          await ctx.model.StoreImage.bulkCreate(imageHashes.map(imageHash => ({
            imageHash, storeId: store.id,
          })));
        }
        ctx.body = await store.update(_.pickBy(
          _.pick(
            ctx.request.body,
            [ 'name', 'status', 'address', 'phone', 'storeType', 'storeCityId', 'commissionRatio', 'storeClassId', 'longitude', 'latitude', 'imageHash', 'fileHash' ]
          ),
          value => value !== null
        ));
      } else {
        ctx.status = 404;
      }
    }
      break;
    default:
  }

};

exports.destroy = async ctx => {
  const currentUser = await ctx.model.User.findByPk(ctx.state.user.sub);
  console.log('exports.update currentUser', currentUser);
  const { role } = currentUser;
  const store = await ctx.model.Store.findByPk(ctx.params.id);
  if (store && role === 'admin') {
    await store.destroy();
    ctx.status = 204;
  } else {
    ctx.status = 404;
  }
};
